<template>
  <div class="tree-page">
    <Card :bordered="true" dis-hover class="ivu-mb">
      <div slot="title">
        <Dropdown>
          <Button type="primary" ghost>
            添加能耗项
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem @click.native="handleOpenCreateHeader"
              >添加顶级能耗项</DropdownItem
            >
            <DropdownItem
              :disabled="currentNode.id==='root'||!isShowBindEquip"
              @click.native="handleOpenCreateSider"
              >添加子能耗项
            </DropdownItem>
          </DropdownMenu>
        </Dropdown>
        <Button
          type="primary"
          ghost
          class="ivu-ml"
          v-show="!toggleExpand"
          @click="handleToggleExpandAll(true)"
        >
          <Icon type="md-list" />
          全部展开
        </Button>
        <Button
          type="primary"
          ghost
          class="ivu-ml"
          v-show="toggleExpand"
          @click="handleToggleExpandAll(false)"
        >
          <Icon type="md-list" />
          全部收起
        </Button>
        <Button
          type="error"
          ghost
          class="ivu-ml"
          v-show="selectedData.length"
          @click="handleDeleteMultiple"
        >
          <Icon type="md-trash" />
          批量删除
        </Button>
      </div>
      <div :style="menuListStyle">
        <div class="ivu-p-8">
          <Input
            v-if="menuList.length || query !== ''"
            v-model="query"
            search
            placeholder="输入能耗项名称搜索"
            @on-change="handleSearch"
          />
        </div>
        <Tree
          :data="menuList"
          show-checkbox
          check-strictly
          @on-select-change="handleSelectNode"
          @on-check-change="handleCheckNode"
          @on-contextmenu="handleContextMenu"
        >
          <template slot="contextMenu" v-if="showContextMenu">
            <DropdownItem @click.native="handleContextMenuEdit" v-show="isShowBindEquip"
              >编辑</DropdownItem
            >
            <DropdownItem @click.native="handleContextMenuRead" v-show="isShowBindEquip"
              >查看</DropdownItem
            >
            <DropdownItem @click.native="handleContextMenuNew" v-show="isShowBindEquip"
              >添加子能耗项</DropdownItem
            >
            <DropdownItem @click.native="bindEquipment" v-show="isShowBindEquip"
              >绑定设备</DropdownItem
            >
            <DropdownItem @click.native="bindMeter" v-show="isShowBindMeter"
              >绑定仪表</DropdownItem
            >
            <DropdownItem
              divided
              @click.native="handleContextMenuDelete"
              style="color: #ed4014"
              >删除
            </DropdownItem>
          </template>
        </Tree>
      </div>
    </Card>
    <new-add-modal
      v-bind="addNewPanel"
      :modelType="modelType"
      :columns="addFormColumns"
      :rules="rules"
      :zIndex="zIndex"
      @submit="handleNewAddSubmit"
    ></new-add-modal>
    <edit-modal
      v-bind="editPanel"
      :modelType="modelType"
      :columns="formColumns"
      :rules="rules"
      :zIndex="zIndex"
      @submit="handleEditSubmit"
    ></edit-modal>
    <read-modal
      v-bind="readPanel"
      :modelType="modelType"
      :columns="columns"
      :rules="rules"
      :zIndex="zIndex"
    ></read-modal>
    <!-- 绑定设备 -->
    <bindEquipNoCategory
        :equipPanel="equipPanel"
        :selectionData="equipSelectionData"
        :selfSelectFilter="selfSelectFilter"
        @submit="handleSelectSubmit">
    </bindEquipNoCategory>
  </div>
</template>

<script>
    import newAddModal from '@/pages/components/newAddModal.vue';
    import editModal from '@/pages/components/editModal.vue';
    import readModal from '@/pages/components/readModal.vue';
    import bindEquipNoCategory from '../../components/bindEquipNoCategory.vue';
    import logicTreeMixin from '@/pages/components/mixins/logicTreeMixin';
    import { typeClassName } from '@/pages/config/classNameMap';
    import columnsMixin from './config'
    export default {
        components: { newAddModal, editModal, readModal, bindEquipNoCategory},
        mixins:[logicTreeMixin,columnsMixin],
        props: {
            classObject: {
                default: () => {
                    return null;
                }
            },
            className: {
                default: () => {
                    return '';
                }
            },
            type: {
                default: () => {
                    return '';
                }
            },
            modelType: {
                default: () => {
                    return '';
                }
            },
            data: {
                default: () => {
                    return [];
                }
            },
            addNewPanel: {
                default: () => {
                    return {
                        width: 1024,
                        zIndex: 100,
                        titleStyle: {},
                        drawer: {
                            show: false
                        },
                        cols: 2
                    }
                }
            },
            editPanel: {
                default: () => {
                    return {
                        width: 1024,
                        zIndex: 100,
                        titleStyle: {},
                        drawer: {
                            show: false
                        },
                        cols: 2,
                        data: {}
                    }
                }
            },
            readPanel: {
                width: 1024,
                zIndex: 100,
                titleStyle: {},
                drawer: {
                    show: false
                },
                cols: 2,
                data: {}
            },
        },
        data () {
            return {
                rules: {
                    sf_code: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    sf_name: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ]
                },
                currentNode: {
                    id: 'root',
                    title: 'root'
                },
                menuList: [],
                sourceMenuList: [],
                zIndex: 1000,
                selectedData: [],
                toggleExpand: true,
                query: '',
                loading: false,
                showContextMenu: true,
                equipSelectionData: [],
                equipPanel: {
                    width: 1024,
                    zIndex: 1000,
                    titleStyle: {},
                    drawer: {
                        show: false
                    },
                    cols: 3,
                    data: {}
                },
                selfSelectFilter:{sf_category:'0'}  //0设备  1仪表
            };
        },
        computed: {
            isShowBindEquip(){
                return !(this.currentNode && this.currentNode.data && this.currentNode.data.pointer && this.currentNode.data.pointer.className===typeClassName['equipment'].className)
            },
            isShowBindMeter(){
                return !(this.currentNode && this.currentNode.data && this.currentNode.data.pointer && this.currentNode.data.pointer.className===typeClassName['equipment'].className&&this.currentNode.data.values['sf_category']==='1')
            },
            menuListStyle () {
                return {
                    height: document.body.clientHeight - 330 + 'px',
                    overflow: 'auto'
                }
            },
        },
        watch: {
            data: {
                handler () {
                    this.menuList = this.getChildren('root')
                    this.sourceMenuList = this.menuList
                },
                deep: true
            }
        },
        mounted () {
            this.menuList = this.getChildren('root')
            this.sourceMenuList = this.menuList
        },
        methods: {
            getChildren (parentId) {
                let children = [];
                let list = this.data.filter(item => item.parentId === parentId);
                list.map(item => {
                    if (!!item.pointer && item.pointer.className === typeClassName['person'].className) {
                        return;
                    }
                    children.push({
                        title: item.values.sf_name ? `${item.values.sf_name}` : item.name,
                        id: item.id,
                        parentId: item.parentId,
                        contextmenu: true,
                        data: item,
                        pointer: item.pointer,
                        children: this.getChildren(item.id)
                    })
                });
                return children;
            },
            // 打开新增能耗项弹窗
            handleContextMenuNew () {
                this.$set(this.addNewPanel.drawer, 'show', true);
            },
            // 新增能耗项保存
            handleNewAddSubmit (data) {
                let newData = {
                    id: this.tools.uuid(8),
                    name: this.tools.uuid(8),
                    title: data.values['sf_name'],
                    values: {
                        ...data.values
                    },
                    pointer: {type:this.type,className:this.className},
                    parentId: this.currentNode.id
                };
                this.$emit('handleNewAddSubmit', newData)
            },
            // 打开编辑能耗项弹窗
            handleContextMenuEdit () {
                this.loading = true;
                if (this.classObject.isValidHier()) {
                    let index = this.classObject.record.hier[0].basic.findIndex(d => d.id === this.currentNode.id)
                    if (index !== -1) {
                        this.$set(this.editPanel, 'data', this.tools.lodash.cloneDeep(this.classObject.record.hier[0].basic[index]));
                        this.$set(this.editPanel.drawer, 'show', true);
                    }
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            },
            // 编辑能耗项保存
            handleEditSubmit (data) {
                let newData = {
                    id: data.id,
                    name: data.name,
                    title: data.name,
                    values: {
                        ...data.values
                    },
                    pointer: {},
                    parentId: !!data.parentId ? data.parentId : 'root'
                };
                this.$emit('handleEditSubmit', newData)
            },
            // 打开查看能耗项弹窗
            handleContextMenuRead () {
                this.loading = true;
                if (!!this.classObject.record && !!this.classObject.record.hier && !!this.classObject.record.hier[0]) {
                    let index = this.classObject.record.hier[0].basic.findIndex(d => d.id === this.currentNode.id)
                    if (index !== -1) {
                        this.$set(this.readPanel, 'data', this.classObject.record.hier[0].basic[index].values);
                        this.$set(this.readPanel.drawer, 'show', true);
                    }
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            },
            // 左击选中
            handleSelectNode (currentArr, item) {
                this.currentNode = { ...item }
                if (!!item.pointer && item.pointer.className === typeClassName['person'].className) {
                    this.showContextMenu = false;
                } else {
                    this.showContextMenu = true;
                }
                this.$emit('handleSelectNode', this.currentNode)
            },
            // 右击
            handleContextMenu (item) {
                this.currentNode = { ...item }
                if (!!item.pointer && item.pointer.className === typeClassName['person'].className) {
                    this.showContextMenu = false;
                } else {
                    this.showContextMenu = true;
                }
                this.$emit('handleSelectNode', this.currentNode)
            },
            // 删除能耗项
            handleContextMenuDelete () {
                if (this.submitting) return;
                this.$Modal.confirm({
                    title: this.lang['confirmDelete'],
                    cancelText: this.lang['cancel'],
                    content: `您确认要删除能耗项<strong>${this.currentNode.title}</strong>吗？`,
                    loading: this.loading,
                    onOk: () => {
                        this.deleteMenu();
                    }
                });
            },
            // 确认删除能耗项
            deleteMenu () {
                let menu = this.data.find(item => item.parentId === this.currentNode.id);
                if (!!menu) {
                    this.$Modal.remove();
                    this.$Message.warning('请先删除子能耗项并解绑设备仪表');
                    return;
                }
                let names = [];
                if (!!this.currentNode.data && !!this.currentNode.data.name) {
                    names = [this.currentNode.data.name]
                }
                let pointer = { className: this.className, type: this.type }
                // 解绑hier中某项的接口
                this.loading = true;
                this.classObject
                    .runRemoveRegister(pointer, names)
                    .then((flag) => {
                        if (flag) {
                            this.loading = false;
                            names.forEach((name) => {
                                let index = this.data.findIndex(
                                    (d) => d.name === name
                                );
                                if (index !== -1) {
                                    this.classObject.record.hier[0].basic.splice(index, 1);
                                }
                            });
                            this.currentNode = {
                                id: 'root',
                                title: '未选中'
                            }
                            this.$emit('handleSelectNode', this.currentNode)
                        } else {
                            this.loading = false;
                        }
                });
            },
            // 批量删除能耗项
            handleDeleteMultiple () {
                if (this.submitting) return;
                const ids = this.selectedData.map(item => item.data.name);
                const titles = this.selectedData.map(item => item.title);
                this.$Modal.confirm({
                    title: this.lang['confirmDelete'],
                    cancelText: this.lang['cancel'],
                    content: `您确认要删除能耗项<strong>${titles}</strong>吗？`,
                    loading: this.loading,
                    onOk: () => {
                        this.deleteMenuMultiple(ids);
                    }
                });
            },
            // 确认批量删除能耗项
            deleteMenuMultiple (names) {
                for (let i = 0; i < names.length; i++) {
                    let menu = this.data.find(item => item.parentId === names[i]);
                    if (!!menu) {
                        this.$Modal.remove();
                        this.$Message.warning('请先删除' + menu.title + '子能耗项并解绑设备仪表');
                        return;
                    }
                }
                let pointer = { className: this.className, type: this.type }
                // 解绑hier中某项的接口
                this.loading = true;
                this.classObject
                    .runRemoveRegister(pointer, names)
                    .then((flag) => {
                        if (flag) {
                            this.loading = false;
                            names.forEach((name) => {
                                let index = this.data.findIndex(
                                    (d) => d.name === name
                                );
                                if (index !== -1) {
                                    this.classObject.record.hier[0].basic.splice(index, 1);
                                }
                            });
                            this.currentNode = {
                                id: 'root',
                                title: '未选中'
                            }
                            this.$emit('handleSelectNode', this.currentNode)
                        } else {
                            this.loading = false;
                        }
                });
            },
            //绑定设备
            bindEquipment () {
                this.equipSelectionData = this.classObject.getChildrenById(this.currentNode.id).map(d=>{
                    return {
                        id: d.id,
                        label: d.values['sf_name'] || ''
                    }
                })
                this.selfSelectFilter['sf_category'] = '0' //0设备  1仪表
                this.$set(this.equipPanel.drawer, 'show', true)
            },
            //绑定仪表
            bindMeter(){
                this.equipSelectionData = this.classObject.getChildrenById(this.currentNode.id).map(d=>{
                    return {
                        id: d.id,
                        label: d.values['sf_name'] || ''
                    }
                })
                this.selfSelectFilter['sf_category'] = '1' //0设备  1仪表
                this.$set(this.equipPanel.drawer, 'show', true)
            },
            handleSelectSubmit (selection) {
                let pointer = { className: this.className, type: this.type, id: this.classObject.record.id }
                let newData = selection.map(d => {
                    return {
                        values: { sf_name: d.label, id: d.id, ...this.selfSelectFilter },
                        name: 'equipment-' + String(d.id),
                        id: d.id,
                        parentId: this.currentNode.id,
                        model: typeClassName['equipment'].modelType,
                        pointer: { id: d.id, className: typeClassName['equipment'].className, type: typeClassName['equipment'].type }
                    }
                })
                let originalData = [];
                if (!!this.classObject.hier && this.classObject.hier.length > 0) {
                    this.classObject.hier[0].basic.forEach(item => {
                        if (item.parentId !== this.currentNode.id) {
                            originalData.push({ ...item })
                        }
                    })
                }
                newData = [...newData, ...originalData]
                // 添加hier中某项的接口
                this.hierAllAddRegister(pointer, newData, this.equipPanel)
            }
        }
    };
</script>
<style scoped lang="scss">
.tree-page{
    width: 600px;
    margin-top: 10px;
}
</style>
